<?php
namespace Management\Controller;
use Myself\FileSystem;
use Think\Controller;
class BaseController extends Controller {



    public function _initialize(){
   		$this->checkUser();
		$this->assign('adminLock',0);  ////开发人员平台开关
		$this->assign('langLock',M('admin_config')->getField('is_language'));  ////多语言版本开关
		$this->assign('mobilePower',M('admin_config')->getField('is_mobile'));  ////手机站开关
//		$this->assign('onlyMobilePower',M('admin_config')->getField('is_only_mobile'));  ////单独手机站开关
//		$this->assign('rightNavMobilePower',M('admin_config')->getField('is_right_nav'));  ////手机站右侧导航开关
//
//
//
//
//		$this->assign('htmlPower',C('CREAT_HTML'));  ////静态页开关
		
		
		
		
		
		$m_lang = M('admin_language');
		$langList = $m_lang->order('list_order desc , id asc')->select();
		$this->assign('langList',$langList);// 赋值数据集



		
		$GLOBALS['notice'] = C('NOTICE');   /////后台相关提示语

       $ma = D('user');
       $mb = M('user_group');
       $m_id = $ma->getAuthInfo('id');
       $m_name = $ma->getAuthInfo('username');
       $group_id = $ma->getAuthInfo('group_id');
       $group_name = $mb->where('id='.$group_id)->getField('group_name');
       $group_keys = $mb->where('id='.$group_id)->getField('group_keys');
       $this->assign('m_id',$m_id);   ////管理员ID
       $this->assign('m_name',$m_name);
       $this->assign('group_name',$group_name);   ////管理员权限组名
       $this->assign('group_keys',$group_keys);   ////管理员权限索引
		
		
		
		
		
		
		
		
		//******以下代码为前台页面进行PvPr值统计使用，请在网站前台嵌套完毕后将此段代码剪切至Home模块的根控制器的自启动方法中******//
		
/*		$mpr = M('guest_pr');
		$mpv = M('guest_pv');
		$guest['addtime'] = strtotime(date('Y-m-d'));
		$guest['ip']      = getIp();
		$mpv->add($guest);
		$isAdd = $mpr->where($guest)->getField('count(*)');
		if(!$isAdd)$mpr->add($guest);*/
		
		//******以上代码为前台页面进行PvPr值统计使用，请在网站前台嵌套完毕后将此段代码剪切至Home模块的根控制器的自启动方法中******//
		
        $this->addLeft();
   }
    public function checkUser(){
   		$user = D('Management/User');
		
		$result = $user->auth();
		!$result && $this->redirect('Login/index');
		
   }
    public function baseDelFile($m,$ids,$field){
		$file = new \Myself\FileSystem();// 实例化上传类
		$config=C("TMPL_PARSE_STRING");//获取相关配置信息
		$pInfo = M($m)->where('id in('.$ids.')')->field($field)->select();
		foreach($pInfo as $item){
			$delpic[]=$config["__AFILE__"].$item[$field];
			$info=pathinfo($item[$field]);
			$delpic[]=$config["__AFILE__"].$info['dirname']."/thumb_".$info["basename"];
		}
		$file->rm($delpic);//删除文件
		return $delpic;
   }
	public function selectPage(){
	
		$para['act'] = I('act');
		$para['back_url'] = I('back_url','','strip_tags');
		$para['jump_url'] = I('jump_url');

		$this->assign('para',$para);
		$this->display('Inc/select_jump');
	}
	public function selectPage_ajax($array){
        $this->ajaxReturn($array);
    }
	private function _deleteDir($R){
        $handle = opendir($R);
        while(($item = readdir($handle)) !== false){
            if($item != '.' and $item != '..'){
                if(is_dir($R.'/'.$item)){
                    $this->_deleteDir($R.'/'.$item);
                }else{
                    if(!unlink($R.'/'.$item))
                        die('clear false...!');
                }
            }
        }
        closedir( $handle );
        return rmdir($R); 
    }
    public function clearRuntime(){
        
        $R = RUNTIME_PATH;
        if($this->_deleteDir($R))
            die("clear over...!");
            
    }
	public function create_all(){
		
		 $result=$this->create_common();
		
		 $result=$this->create_news();
		 $result=$this->creatIndexPage();
		if($result){
			HtmlMd5('Index');$this->success('文件生成完毕');		
		}else{
			$this->error('文件生成失败');
		}
		
	}
	private function create_common(){
		$ids=M('common')->field('id')->where('common_id = 0')->select();
		
		if(!$ids){
			$this->error('参数错误');
			return;
		}
		foreach($ids as $v){
			$id=$v['id'];
			$dataInfo = M('common')->find($id);
			$mob_controller = $dataInfo['mob_controller'];
			if(!$mob_controller){
				$this->error('需要先填入控制器名称');
				return;
			}
			if(preg_match("/[^A-Za-z]/",$mob_controller)){
				$this->error('控制器只能由字母组成');
				return;
			}
			$lowercontroller = strtolower($mob_controller);
			$mob_controller = ucfirst($lowercontroller);
			
			$patternArray=array('/1/','/About/');
			$replaceArray = array(''.$id,$mob_controller);
			$templatePath = rtrim(__PHYSICS__,'\\').'/App/Template/Home/';
			$destPath = rtrim(__PHYSICS__,'\\').'/App/Home/';
			
			$this->create_page($templatePath,$destPath,'Controller/AboutController.class.php','Controller/'.$mob_controller.'Controller.class.php',$patternArray,$replaceArray);
			$this->create_page($templatePath,$destPath,'View/Pages/about.tpl','View/Pages/'.$lowercontroller.'.tpl',array('/About/'),array($mob_controller));
			
			
		}
	
	}
	private function create_news(){
        $ids=M(news_config)->field('id')->select();
        foreach($ids as $v){
            $id=$v['id'];
            $dataInfo = M(news_config)->find($id);
            $pc_controller = $dataInfo['pc_controller'];
            if(!$pc_controller){
                $this->error('需要先填入控制器名称');
                return;
            }
            if(preg_match("/[^A-Za-z]/",$pc_controller)){
                $this->error('控制器只能由字母组成');
                return;
            }
            $lowercontroller = strtolower($pc_controller);
            $pc_controller = ucfirst($lowercontroller);

            $patternArray=array('/999/','/Honor/');
            $replaceArray = array(''.$id,$pc_controller);
            $templatePath = rtrim(__PHYSICS__,'\\').'/App/Template/Home/';
            $destPath = rtrim(__PHYSICS__,'\\').'/App/Home/';

            $this->create_page($templatePath,$destPath,'Controller/HonorController.class.php','Controller/'.$pc_controller.'Controller.class.php',$patternArray,$replaceArray);
            $this->create_page($templatePath,$destPath,'View/Pages/honor_a.tpl','View/Pages/'.$lowercontroller.'_a.tpl',array('/Honor/'),array($pc_controller));
            $this->create_page($templatePath,$destPath,'View/Pages/honor_b.tpl','View/Pages/'.$lowercontroller.'_b.tpl',array('/Honor/'),array($pc_controller));
            $this->create_page($templatePath,$destPath,'View/Pages/honor_c.tpl','View/Pages/'.$lowercontroller.'_c.tpl',array('/Honor/'),array($pc_controller));
            $this->create_page($templatePath,$destPath,'View/Pages/honor_d.tpl','View/Pages/'.$lowercontroller.'_d.tpl',array('/Honor/'),array($pc_controller));
            $this->create_page($templatePath,$destPath,'View/Pages/honor_view.tpl','View/Pages/'.$lowercontroller.'_view.tpl',array('/Honor/'),array($pc_controller));
//
        }
		
		
    }
	private function creatIndexPage(){
		$list = M('web_mobile_index')->where(array('status'=>1))->order('list_order desc')->select();
		$indexStr="";
		foreach ($list as $key=>$item){
			$indexStr.="<assign name=\"datasource\" value=\"".$item['datasource']."\"/>"."\n";
			$indexStr.="<assign name=\"datasource2\" value=\"".$item['datasource2']."\"/>"."\n";
			$indexStr.="<assign name=\"indexInfo\" value=\""."$"."indexPageList.".$key."\"/>"."\n";
			//$indexStr.="{"."$"."indexInfo.module_name}"."\n";
			$indexStr.="<include file=\"Inc/".$item['module_key']."\"/>"."\n";
		}
		$templatePath = rtrim(__PHYSICS__,'\\').'/App/Template/Home/View/Pages/index.tpl';
		$destPath = rtrim(__PHYSICS__,'\\').'/App/Home/View/Pages/index.tpl';
		$template_context=file_get_contents($templatePath);
		$result_context = str_replace("{IndexContent}",$indexStr,$template_context);
		if(file_put_contents($destPath,$result_context)){
			return true;			 
		}else{
			return false;
		} 
		
		
		
		
	}
	private function create_page($templatePath,$destPath,$templateFile,$destFile,$patternArray,$replaceArray){
		ob_clean();
		$templateStr = file_get_contents($templatePath.$templateFile);
		
		$templateStr = mb_convert_encoding($templateStr,'UTF-8',"auto");
		
		$resultStr = preg_replace($patternArray,$replaceArray,$templateStr);
		
		if(file_put_contents($destPath.$destFile,$resultStr)){			
			return true;			 
		}else{
			return false;
		} 
		
		ob_flush();
	}
    private function addLeft(){
        header('Content-Type:text/html;charset=utf-8');

        $subNav = C('NAV');

//        $moduleList = D('Base')->listModules();

//        foreach($moduleList as $item){
//            $itemNav = $this->getModuleNav($item);
//            if($itemNav){
//                $subNav[$item."ExtraManage"] =$itemNav;
//            }
//        }
        //die(json_encode($subNav));

        $mobilePower = M('admin_config')->getField('is_mobile');

//        if(!$mobilePower){
//            unset($subNav['mobileManage']);
//        }

        if(!C('SHOP_POWER')){
            unset($subNav['shopManage']);
        }
        if(!C('MEM_POWER')){
            unset($subNav['memberManage']);
        }



        $this->assign('subNav',$subNav);

        //$this->display('left');
    }
    protected function pic_move($pic_new,$pic_old){
        $config=C("TMPL_PARSE_STRING");//获取相关配置信息
        $picArr=explode(',',$pic_new);
        $pic_path=$picArr[1].$picArr[3]; // 实际保存数据库路径地址
        $fromPath=$picArr[0].$picArr[2];//源文件夹
        $ToPath=$picArr[0].$picArr[1];//目标文件夹
        $file[]=$picArr[3];
        FileSystem::mv($file , $fromPath , $ToPath );
        FileSystem::mv($file , 'Thumb'.$fromPath , 'Thumb'.$ToPath);
        $delpic=$config["__AFILE__"].$pic_old;
        FileSystem::rm($delpic);//删除原图
        return $pic_path;
    }
    protected function video_move($video_new,$temp){
        $config=C("TMPL_PARSE_STRING");//获取相关配置信息
        $pic=$temp['video_path'];
        $picArr=explode(',',$video_new);
        $temp['video_path']=$picArr[1].$picArr[3]; // 实际保存数据库路径地址
        $fromPath=$picArr[0].$picArr[2];//源文件夹
        $ToPath=$picArr[0].$picArr[1];//目标文件夹
        $file[]=$picArr[3];
        $file[]="thumb_".$picArr[3];
        FileSystem::mv($file , $fromPath , $ToPath , 'k');
        $delpic=$config["__AFILE__"].$pic;
        FileSystem::rm($delpic);//删除原图
        return $temp['video_path'];
    }

    protected function file_move($file_new,$temp){
        $config=C("TMPL_PARSE_STRING");//获取相关配置信息
        $pic=$temp['file_path'];
        $picArr=explode(',',$file_new);
        $temp['file_path']=$picArr[1].$picArr[3]; // 实际保存数据库路径地址
        $fromPath=$picArr[0].$picArr[2];//源文件夹
        $ToPath=$picArr[0].$picArr[1];//目标文件夹
        $file[]=$picArr[3];
        FileSystem::mv($file , $fromPath , $ToPath);
        $delpic=$config["__AFILE__"].$pic;
        FileSystem::rm($delpic);//删除原图
        return $temp['file_path'];
    }
}